import com.sun.deploy.net.HttpUtils;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class HttpHandle extends ChannelInboundHandlerAdapter {

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        FullHttpRequest request = (FullHttpRequest) msg;
        log.info("http request url={}", request.getUri());
        log.info("http request method={}", request.getMethod());

        try {
            String content = "hello my netty server";
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1
                    , HttpResponseStatus.OK
                    , Unpooled.wrappedBuffer(content.getBytes(StandardCharsets.UTF_8)));

            response.headers().set("Content-Type", "application/json");
            response.headers().set("Content-Length", content.length());

            ctx.write(response).addListener(ChannelFutureListener.CLOSE);

        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
